/**
 * 
 */
package com.effectivsocial.extension.plugin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import au.com.bytecode.opencsv.bean.CsvToBean;

import com.effectivsocial.domain.Link;
import com.effectivsocial.domain.LinkGroup;
import com.effectivsocial.service.api.LinkGroupService;
import com.effectivsocial.service.api.LinkService;
import com.effectivsocial.service.api.ViewDefinitionService;

/**
 * @author Dhrubo
 * 
 */
@Named
@Slf4j
public class NavigationDefinitionLoaderPlugin implements StartupPlugin {

	private final String LINK_GROUP_FILE_PATTERN = "classpath:/META-INF/menu/linkgroup.csv";
	private final String LINK_GROUP_VIEW_FILE_PATTERN = "classpath:/META-INF/menu/linkgroupview.csv";
	private final String LINK_GROUP_LINK_FILE_PATTERN = "classpath:/META-INF/menu/linkgrouplink.csv";
	private final String LINK_FILE_PATTERN = "classpath:/META-INF/menu/link.csv";

	@Inject
	private LinkService linkService;

	@Inject
	private LinkGroupService linkGroupService;
	
	@Inject
	private ViewDefinitionService viewDefinitionService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.effectivcrm.extension.plugin.StartupPlugin#preProcess(org.springframework
	 * .context.ApplicationContext)
	 */
	public void preProcess(ApplicationContext ctx) {
		
		CSVReader reader = null;
		
		
		linkGroupService.deleteAllAssociatedLinks();
		
		
		log.info("Deleting all links");
		List<Link> links = linkService.findAll();
		linkService.purge(links);

		log.info("Deleting all link groups");
		List<LinkGroup> linkGroups = linkGroupService.findAll();
		linkGroupService.purge(linkGroups);

		// load link group

		Resource[] resources;

		ColumnPositionMappingStrategy<LinkGroup> strategy = new ColumnPositionMappingStrategy<LinkGroup>();
		String columns[] = {"name", "labelKey", "position" ,"href"};
		strategy.setType(LinkGroup.class);
		strategy.setColumnMapping(columns);
		CsvToBean<LinkGroup> csv = new CsvToBean<LinkGroup>();

		List<LinkGroup> entities = null;
		try {

			resources = ctx.getResources(LINK_GROUP_FILE_PATTERN);
			
			
			for (Resource resource : resources) {
				if (log.isInfoEnabled()) {
					log.info("## Processing resource = {}", resource);
				}
				
				reader = new CSVReader(new BufferedReader(
						new InputStreamReader(resource.getInputStream())), ',', '\'', 1);
				
				entities = csv.parse(strategy, reader);
				log.info("Link Groups to be loaded - {}", entities.size());

				linkGroupService.save(entities);
			}

		} catch (Exception e) {
			log.error("Error", e);
		}

		// load links
		ColumnPositionMappingStrategy<Link> linkStrategy = new ColumnPositionMappingStrategy<Link>();
		
		String linkColumns[] = { "name", "labelKey", "href" , "linkType"};
		linkStrategy.setType(Link.class);
		linkStrategy.setColumnMapping(linkColumns);
		CsvToBean<Link> linkCsv = new CsvToBean<Link>();

		List<Link> linkEntities = null;

		try {

			resources = ctx.getResources(LINK_FILE_PATTERN);

			for (Resource resource : resources) {
				if (log.isInfoEnabled()) {
					log.info("## Processing resource = {}", resource);
				}
				
				reader = new CSVReader(new BufferedReader(
						new InputStreamReader(resource.getInputStream())), ',', '\'', 1);
				
				linkEntities = linkCsv.parse(linkStrategy, reader);
				log.info("Link Entities to be loaded - {}",linkEntities);

				linkService.save(linkEntities);
			}

		} catch (Exception e) {
			log.error("Error", e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.effectivcrm.extension.plugin.StartupPlugin#process(org.springframework
	 * .context.ApplicationContext)
	 */
	public void process(ApplicationContext ctx) {
		CSVReader reader = null;
		
		// load and associate view to link group
		try {
			Resource[] resources = ctx
					.getResources(LINK_GROUP_VIEW_FILE_PATTERN);
				
			for (Resource resource : resources) {
				
				reader = new CSVReader(new BufferedReader(
						new InputStreamReader(resource.getInputStream())), ',', '\'', 1);
				
				
				String[] nextLine;
				while ((nextLine = reader.readNext()) != null) {
					viewDefinitionService.appendLinkGroup(nextLine[0], nextLine[1]);
				}
			}
		} catch (Exception e) {
			log.error("Error", e);
		}
		// load and associate link to link group
		
		try {
			Resource[] resources = ctx
					.getResources(LINK_GROUP_LINK_FILE_PATTERN);

			for (Resource resource : resources) {
				reader = new CSVReader(new BufferedReader(
						new InputStreamReader(resource.getInputStream())), ',', '\'', 1);
				
				String[] nextLine;
				while ((nextLine = reader.readNext()) != null) {
									
					linkGroupService.appendLink(nextLine[0], nextLine[1]);
				}
			}
		} catch (Exception e) {
			log.error("Error", e);
		}
		
		
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.effectivcrm.extension.plugin.StartupPlugin#postProcess(org.
	 * springframework.context.ApplicationContext)
	 */
	public void postProcess(ApplicationContext ctx) {
		// load and associate role to link

		// load and associate role to link group

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.effectivcrm.extension.plugin.StartupPlugin#getOrder()
	 */
	public int getOrder() {
		return 800;
	}

}
